package _dp_base;

/**
 * 516. 最长回文子序列
 */
public class No516 {
    private String s;

    /**
     * 1. 递归
     */
    public int longestPalindromeSubseq1(String s) {
        this.s = s;
        int n = s.length();

        return dfs(0, n - 1);
    }

    private int dfs(int i, int j) {
        if (i == j) return 1;
        else if (i > j) return 0;
        else if (s.charAt(i) == s.charAt(j)) return dfs(i + 1, j - 1) + 2;
        else return Math.max(dfs(i + 1, j), dfs(i, j - 1));
    }

    /**
     * 2. 迭代
     */
    public int longestPalindromeSubseq2(String s) {
        int n = s.length();

        int[][] f = new int[n][n];
        for (int i = n - 1; i >= 0; i--) {
            f[i][i] = 1;
            for (int j = i; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) f[i][j] = f[i + 1][j - 1] + 2;
                else f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]);
            }
        }

        return f[0][n - 1];
    }

    /**
     * 4. 空间优化
     */
    public int longestPalindromeSubseq4(String s) {
        int n = s.length();

        int[] f = new int[n];
        for (int i = n - 1; i >= 0; i--) {
            f[i] = 1;
            int pre = 0;
            for (int j = i + 1; j < n; j++) {
                int temp = f[j];
                if (s.charAt(i) == s.charAt(j)) f[j] = pre + 2;
                else f[j] = Math.max(f[j], f[j - 1]);
                pre = temp;
            }
        }

        return f[n - 1];
    }
}
